using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AutoUpdaterDotNET;
using System.Reflection;
using System.IO;
using Newtonsoft.Json;

namespace DidaManager.Native
{
    public class VersionCheckUpate
    {
        private readonly string _updateUrl;
        private readonly string _currentVersion;
        private readonly UpdateConfig _config;
        private string _downloadPath = string.Empty;

        public VersionCheckUpate(string updateUrl = "")
        {
            _config = LoadUpdateConfig();
            _updateUrl = !string.IsNullOrEmpty(updateUrl) ? updateUrl : _config.UpdateUrl;
            _currentVersion = GetCurrentVersion();
        }

        /// <summary>
        /// 获取当前应用程序版本
        /// </summary>
        /// <returns>当前版本号</returns>
        private string GetCurrentVersion()
        {
            try
            {
                var assembly = Assembly.GetExecutingAssembly();
                var version = assembly.GetName().Version;
                return version?.ToString() ?? "1.0.0.0";
            }
            catch
            {
                return "1.0.0.0";
            }
        }

        /// <summary>
        /// 检查更新（使用默认更新方式）
        /// </summary>
        /// <param name="updateUrl">更新服务器URL</param>
        /// <returns>检查结果</returns>
        public async Task<UpdateCheckResult> CheckForUpdatesAsync(string updateUrl = "")
        {
            try
            {
                var url = !string.IsNullOrEmpty(updateUrl) ? updateUrl : _updateUrl;
                
                if (string.IsNullOrEmpty(url))
                {
                    return new UpdateCheckResult
                    {
                        Success = false,
                        Message = "更新URL未配置",
                        CurrentVersion = _currentVersion
                    };
                }

               //FIXME:
                // 设置下载路径为当前运行目录下的 update_temp 文件夹
                _downloadPath = Path.Combine(Application.StartupPath, "update_temp");
                if (!Directory.Exists(_downloadPath))
                {
                    Directory.CreateDirectory(_downloadPath);
                }                
                // AutoUpdater.InstallationPath = _downloadPath;// 安装路径不能改
                AutoUpdater.DownloadPath = _downloadPath;//解压路径
                AutoUpdater.RunUpdateAsAdmin = false;//设定不需要管理员权限

                // 配置AutoUpdater使用默认更新方式
                if (_config.ShowUpdateDialog)
                {
                    AutoUpdater.ShowSkipButton = true;
                    AutoUpdater.ShowRemindLaterButton = true;
                }
                else
                {
                    AutoUpdater.ShowSkipButton = false;
                    AutoUpdater.ShowRemindLaterButton = false;
                }

                // 使用默认的更新检查和处理流程
                await Task.Run(() => AutoUpdater.Start(url));
                
                return new UpdateCheckResult
                {
                    Success = true,
                    HasUpdate = false, // 默认方式下无法直接获取是否有更新的状态
                    Message = "已启动更新检查",
                    CurrentVersion = _currentVersion,
                    LatestVersion = _currentVersion
                };
            }
            catch (Exception ex)
            {
                return new UpdateCheckResult
                {
                    Success = false,
                    Message = $"检查更新时发生异常: {ex.Message}",
                    CurrentVersion = _currentVersion
                };
            }
        }

        /// <summary>
        /// 同步检查更新方法
        /// </summary>
        /// <param name="updateUrl">更新服务器URL</param>
        /// <returns>检查结果</returns>
        public UpdateCheckResult CheckForUpdates(string updateUrl = "")
        {
            try
            {
                return CheckForUpdatesAsync(updateUrl).GetAwaiter().GetResult();
            }
            catch (Exception ex)
            {
                return new UpdateCheckResult
                {
                    Success = false,
                    Message = $"检查更新时发生异常: {ex.Message}",
                    CurrentVersion = _currentVersion
                };
            }
        }

        /// <summary>
        /// 简单的版本检查方法（真正从服务器获取版本信息但不弹出对话框）
        /// </summary>
        /// <param name="updateUrl">更新服务器URL</param>
        /// <returns>检查结果</returns>
        public UpdateCheckResult SimpleCheckForUpdates(string updateUrl = "")
        {
            try
            {
                var url = !string.IsNullOrEmpty(updateUrl) ? updateUrl : _updateUrl;
                
                if (string.IsNullOrEmpty(url))
                {
                    return new UpdateCheckResult
                    {
                        Success = false,
                        Message = "更新URL未配置",
                        CurrentVersion = _currentVersion
                    };
                }

                // 使用HttpClient从服务器获取版本信息
                using (var client = new System.Net.Http.HttpClient())
                {
                    client.Timeout = TimeSpan.FromSeconds(30);
                    
                    var response = client.GetAsync(url).GetAwaiter().GetResult();
                    if (!response.IsSuccessStatusCode)
                    {
                        return new UpdateCheckResult
                        {
                            Success = false,
                            Message = $"无法连接到更新服务器: {response.StatusCode}",
                            CurrentVersion = _currentVersion
                        };
                    }

                    var xmlContent = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
                    
                    // 解析XML获取版本信息（AutoUpdater使用XML格式）
                    var updateInfo = ParseUpdateXml(xmlContent);
                    
                    if (updateInfo == null)
                    {
                        return new UpdateCheckResult
                        {
                            Success = false,
                            Message = "无法解析服务器返回的版本信息",
                            CurrentVersion = _currentVersion
                        };
                    }

                    // 比较版本
                    var currentVer = new Version(_currentVersion);
                    var latestVer = new Version(updateInfo.Version);
                    var hasUpdate = latestVer > currentVer;

                    return new UpdateCheckResult
                    {
                        Success = true,
                        HasUpdate = hasUpdate,
                        Message = hasUpdate ? "发现新版本" : "当前已是最新版本",
                        CurrentVersion = _currentVersion,
                        LatestVersion = updateInfo.Version,
                        DownloadUrl = updateInfo.DownloadUrl,
                        ChangeLog = updateInfo.ChangeLog
                    };
                }
            }
            catch (Exception ex)
            {
                return new UpdateCheckResult
                {
                    Success = false,
                    Message = $"检查更新时发生异常: {ex.Message}",
                    CurrentVersion = _currentVersion
                };
            }
        }

        /// <summary>
        /// 解析AutoUpdater XML格式的更新信息
        /// </summary>
        /// <param name="xmlContent">XML内容</param>
        /// <returns>更新信息</returns>
        private UpdateInfo ParseUpdateXml(string xmlContent)
        {

            try
            {
                var doc = new System.Xml.XmlDocument();
                doc.LoadXml(xmlContent);

                var versionNode = doc.SelectSingleNode("//version");
                var urlNode = doc.SelectSingleNode("//url");
                var changelogNode = doc.SelectSingleNode("//changelog");

                if (versionNode == null || urlNode == null)
                {
                    return new UpdateInfo();
                }

                return new UpdateInfo
                {
                    Version = versionNode.InnerText,
                    DownloadUrl = urlNode.InnerText,
                    ChangeLog = changelogNode?.InnerText ?? ""
                };
            }
            catch
            {
                return new UpdateInfo();
            }
        }

        /// <summary>
        /// 加载更新配置文件
        /// </summary>
        /// <returns>更新配置</returns>
        private UpdateConfig LoadUpdateConfig()
        {
            try
            {
                var configPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "config", "update-config.json");
                if (File.Exists(configPath))
                {
                    var configContent = File.ReadAllText(configPath);
                    var config = JsonConvert.DeserializeObject<UpdateConfig>(configContent);
                    return config ?? new UpdateConfig();
                }
            }
            catch (Exception ex)
            {
                // 记录日志但不抛出异常
                System.Diagnostics.Debug.WriteLine($"读取更新配置文件失败: {ex.Message}");
            }
            return new UpdateConfig();
        }
    }

    /// <summary>
    /// 更新配置
    /// </summary>
    public class UpdateConfig
    {
        /// <summary>
        /// 更新服务器URL
        /// </summary>
        public string UpdateUrl { get; set; } = string.Empty;

        /// <summary>
        /// 检查间隔（小时）
        /// </summary>
        public int CheckInterval { get; set; } = 24;

        /// <summary>
        /// 是否自动检查
        /// </summary>
        public bool AutoCheck { get; set; } = true;

        /// <summary>
        /// 是否显示更新对话框
        /// </summary>
        public bool ShowUpdateDialog { get; set; } = true;
    }

    /// <summary>
    /// 更新信息
    /// </summary>
    public class UpdateInfo
    {
        /// <summary>
        /// 版本号
        /// </summary>
        public string Version { get; set; } = string.Empty;

        /// <summary>
        /// 下载URL
        /// </summary>
        public string DownloadUrl { get; set; } = string.Empty;

        /// <summary>
        /// 更新日志
        /// </summary>
        public string ChangeLog { get; set; } = string.Empty;
    }

    /// <summary>
    /// 更新检查结果
    /// </summary>
    public class UpdateCheckResult
    {
        /// <summary>
        /// 检查是否成功
        /// </summary>
        public bool Success { get; set; }

        /// <summary>
        /// 是否有更新
        /// </summary>
        public bool HasUpdate { get; set; }

        /// <summary>
        /// 消息
        /// </summary>
        public string Message { get; set; } = string.Empty;

        /// <summary>
        /// 当前版本
        /// </summary>
        public string CurrentVersion { get; set; } = string.Empty;

        /// <summary>
        /// 最新版本
        /// </summary>
        public string LatestVersion { get; set; } = string.Empty;

        /// <summary>
        /// 下载URL
        /// </summary>
        public string DownloadUrl { get; set; } = string.Empty;

        /// <summary>
        /// 更新日志URL
        /// </summary>
        public string ChangeLog { get; set; } = string.Empty;
    }
}
